﻿@*
    // Copyright (c) Alex Reich.
    // Licensed under the CC BY 4.0 License.
*@
@page "/Demo/{WorkflowName?}"
@using Newtonsoft.Json
@using RulesEngine.Models
@using RulesEngineEditor.Models
@using System.IO

<RulesEngineEditorPage EditorRulesEngine="re" @bind-Workflows="Workflows" InputJSON="@Inputs" CurrentWorkflowName="@WorkflowName" />

@code {
    [Parameter]
    public string WorkflowName { get; set; }
    private RulesEngine.RulesEngine re;

    private Workflow[] _workflows;
    private Workflow[] Workflows { get { return _workflows; } set { _workflows = value; } }

    private string _inputs;
    private string Inputs { get { return _inputs; } set { _inputs = value; } }

    enum FooEnum
    {
        bar = 123
    }

    protected override void OnInitialized()
    {
        var settings = new ReSettings
        {
            CustomTypes = new Type[] { typeof(FooEnum) }
        };
        re = new RulesEngine.RulesEngine(new string[0], settings);

#if BasicDemo
List<Workflow> Workflow = new List<Workflow>();
Workflow workflowRule = new Workflow();
workflowRule.WorkflowName = "Test Workflow Rule 1";

List<Rule> rules = new List<Rule>();

Rule rule = new Rule();
rule.RuleName = "Test Rule";
rule.SuccessEvent = "Count is within tolerance.";
rule.ErrorMessage = "Over expected.";
rule.Expression = "count < 3";
rule.RuleExpressionType = RuleExpressionType.LambdaExpression;

rules.Add(rule);

workflowRule.Rules = rules;

Workflow.Add(workflowRule);

Workflows = Workflow.ToArray();
#endif

        var path = Path.Combine(Directory.GetCurrentDirectory(), @"..\TestData\");
        var files = Directory.GetFiles(path, "Discount.json", SearchOption.AllDirectories);
        if (files == null || files.Length == 0)
            throw new Exception("Rules not found.");

        var fileData = File.ReadAllText(files[0]);
        var workflow = JsonConvert.DeserializeObject<List<Workflow>>(fileData);

        files = Directory.GetFiles(path, "DiscountInputs.json", SearchOption.AllDirectories);
        if (files == null || files.Length == 0)
            throw new Exception("Inputs not found.");

        Workflows = workflow.ToArray();
        Inputs = File.ReadAllText(files[0]);
    }
}